<template>
	<view>
		<view class="u-p-26">

			<view class="u-p-28 bg-white u-flex u-col-top  goodItem">
				<u-image :src="goodDetail.mainImage" width="140" height="140" bg-color="#ffc300"></u-image>
				<view class="u-flex-1 u-p-l-24">
					<view class="u-font-lg fw-large" style="color: #6b6b6b;">{{goodDetail.name}}</view>
					<view class="u-font-xs color-gary-xs u-m-t-6">原价:{{goodDetail.price}}</view>
					<view class="u-font-xs color-gary-xs ">优惠价:{{goodDetail.salePrice}}</view>
					<view class="u-flex  u-row-right u-m-t-6">
						<u-icon color="#6b6b6b" label-color="#6b6b6b" name="map" size="28"
							:label="goodDetail?.businessVillage?.name"></u-icon>
					</view>
				</view>

			</view>

			<view class="u-m-t-18 bg-white">
				<block v-for="(item,index) in list" :key="index">
					<view class="u-font-sm fw-large u-p-t-20 u-p-b-14 u-p-l-8">{{item.specName}}</view>
					<u-grid :border='false' :col="4">

						<u-grid-item @click="selectClick(items)" :custom-style="custItem"
							v-for="(items,indexs) in item.specValList" :key="indexs">
							<view class="seleBtn line-1 " :style="item.disabled?'opacity: .3;':''"
								@click="item.disabled?'':clickSelect(items,indexs)" :class="items.select?'active':''">
								{{items.specVal}}
							</view>
						</u-grid-item>
					</u-grid>
				</block>
			</view>


			<view class="u-m-t-58 bg-white u-p-t-28 u-p-l-26 u-p-r-26">
				<view v-if="type==2" class="fw-large u-font-lg u-text-center">设置库存状态</view>
				<u-form labelWidth="auto">
					<u-form-item label="库存">
						<template #right>
							<u-number-box v-model="goodDetail.stock" :max="999999999"></u-number-box>
						</template>
					</u-form-item>
					<u-form-item label="状态">
						<template #right>
							<u-radio-group v-model="goodDetail.saleState" @change="handleEventTypeChange">
								<u-radio :name="2">上架</u-radio>
								<u-radio :name="3">下架</u-radio>
								<u-radio :name="4">售罄</u-radio>
							</u-radio-group>
						</template>
					</u-form-item>
				</u-form>
			</view>

			<view class="u-m-t-80">
				<u-button @click="seleAll" v-if="type==2" type="primary"
					style="box-shadow: 0upx 2upx 6upx rgba(200, 200, 200,.4);">全部选中</u-button>
				<view class="u-m-t-30">
					<u-button @click="setGoodsData('select')" type="warning"
						style="box-shadow: 0upx 2upx 6upx rgba(200, 200, 200,.4);">确认修改</u-button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { computed, reactive, ref } from "vue";
	import { onLoad } from '@dcloudio/uni-app'

	import goodsApi from '@/api/goods'

	const list = ref([])
	const variantMap = ref([])
	const varKye = ref([])

	const btnCust = reactive({
		height: '60upx',
		width: '100%'
	})

	const custItem = reactive({
		padding: '15rpx 10rpx',
	})

	const goodDetail = ref({})
  const goodStock = ref<number>(0)

	const type = ref()
	const goodid = ref()

	function clickSelect(items, ids) {
		items.select = !items.select
	}


	function seleAll(){
		list.value.map((item,index)=>{
			item.specValList.map((items)=>{
				items.select = true
			})
		})
	}



	//保存
	function setGoodsData(str) {
		uni.showLoading({
			title: '加载中...'
		})

		let obj = {
			goodsId: goodid.value,
			stock: goodDetail.value.stock,
			saleState: goodDetail.value.saleState
		}
		switch (type.value) {
			case '1':

				break;
			case '2':
				if (str == 'select') {//多选
					let ids = []
					let newVar = []

					let arrs = []
					list.value.map(item => {
						let lis = item.specValList.filter(item => item.select)
						arrs.push(lis.map(items => items.specVal))
					})
					function generateCombinations(arr, index, currentCombination, result) {
						if (index === arr.length) {
							result.push([...currentCombination]);
							return;
						}
						for (const item of arr[index]) {
							currentCombination.push(item);
							generateCombinations(arr, index + 1, currentCombination, result);
							currentCombination.pop();
						}
					}
					const result = [];
					generateCombinations(arrs, 0, [], result);

					let strArr = result.map(item => {
						return item.join(':')
					})


					// console.log("共组合条数:", result.length);

					//判读套餐sku列表key相交
					function findIntersection(array1, array2) {
						return array1.filter(item => array2.includes(item));
					}
					let skulist = findIntersection(strArr, varKye.value)

					let skuids = []
					skulist.map(item => {
						skuids.push(variantMap.value[item].variantId)
					})

					obj.list = skuids




				}


				break;
		}

    if (obj.saleState !==4 && obj.stock === 0) {
      uni.showToast({title: '库存不可为0', icon: 'none'})
      return
    }
		goodsApi.setGoodsData(obj).then(res => {
			uni.hideLoading()
			uni.showToast({
				title:res.msg
			})
			uni.$emit('SETGOOD', goodid.value, goodDetail.value)

		}).catch(() => {
			uni.hideLoading()
		})
	}


	onLoad(async (options) => {// type 1 单品 2 多规格
		type.value = options.type
		goodid.value = options.id
		uni.showLoading({
			title: '加载中...'
		})
		try {
			//  商品详情
			let goods = await goodsApi.goods({ id: options.id })
			if (goods) {
				goodDetail.value = {...goods.data}
        goodStock.value = goods.data.stock
			}

      handleEventTypeChange(goodDetail.value.saleState)

			if (options.type == 2) {
				//查询变体
				let goodScop = await goodsApi.getSpecByGoodsId({ goodsId: options.id })
				if (goodScop) {
					//选中默认
					goodScop.data.specList.map((item, index) => {
						item.specValList.find(items => {
							if (items.specVal == goodScop.data.defaultVariant.sku.split(':')[index]) {
								items.select = true
							}
						})
					})

					list.value = goodScop.data.specList
					variantMap.value = goodScop.data.variantMap
					varKye.value = Object.keys(variantMap.value)
					goodDetail.value.stock = goodScop.data.defaultVariant.stock
				}
			}
		} catch (res) {
			uni.showModal({
				title: '查询错误',
				content: '请联系管理员',
				confirmText: '返回',
				showCancel: false,
				success: (res) => {
					uni.navigateBack()
				}
			})
		} finally {
			uni.hideLoading()
		}

	})


  /**
   * 状态类型change
   * @param type
   */
  const handleEventTypeChange = (type: number) => {
    if (type === 4) {
      goodDetail.value ={...goodDetail.value, stock: 0}
    } else {
      goodDetail.value ={...goodDetail.value, stock: goodStock.value}
    }
  }
</script>


<style lang="scss" scoped>
	.goodItem {
		border-radius: 18upx;
		box-shadow: 0upx 2upx 2upx rgba(100, 100, 100, .2);

	}

	.seleBtn {
		width: 100%;
		line-height: 56upx;
		height: 56upx;
		text-align: center;
		padding: 0 4upx;
		border-radius: 4upx;
		border: 1upx solid #8a8a8a;
		color: #8d8e8c;
	}

	.seleBtn.active {
		background-color: #ffc300;
		color: white;
		border-color: transparent;
	}
</style>

<style scoped>
	page {
		background-color: #f9f9f9;
	}
</style>
